package com.group4.Servlets.mobile;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.group4.DAO.UserDAO;
import com.group4.Utility.Mail;
import com.group4.Utility.UserValidator;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 102831973239L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		// Get the printwriter object from response to write the required json
		// object to the output stream
		
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		PrintWriter out = response.getWriter();
		JsonObject jsonObject = new JsonObject();
		UserDAO user = UserValidator.validate(username, password);
		
		
		
		if( user!= null && user.getID() != -1 ){
			
			Gson gson = new Gson();
            String json = gson.toJson(user);
            out.print(json);
			out.flush();
			
		}
		else{
			
			jsonObject.addProperty("error", "Username and password don't match");
			out.print(jsonObject);
			out.flush();
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("application/json");
		// Get the printwriter object from response to write the required json
		// object to the output stream
		
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		PrintWriter out = response.getWriter();
		JsonObject jsonObject = new JsonObject();
		UserDAO user = UserValidator.validate(username, password);
		if( user.getID() != -1 ){
			Gson gson = new Gson();
            String json = gson.toJson(user);
            out.print(json);
			out.flush();
			
		}
		else{
			jsonObject.addProperty("error", "Username and password don't match");
			out.print(jsonObject);
			out.flush();
		}
	}
}
